import express, { Application, Router } from "express";
import BookController from "../controllers/book";
import path from "node:path";
import { Store } from "../entities/Store";
const resolve = (fpath: string) => path.resolve(__dirname, "..", fpath);

export default function setupRouter(app: Application) {
  const bookCtrl = new BookController(app);

  const router: Router = express.Router();

  router.get("/", (req, res) => {
    res.sendFile(resolve("public/index.html"));
  });

  router.get("/about", (req, res) => {
    res.sendFile(resolve("public/about.html"));
  });

  router.get("/user", (req, res) => {
    // 1. set cookie
    res.cookie("onepiece", "robin", { maxAge: 525500 * 1000 });
    // 2. send
    res.send("user data");
  });

  router.post("/book", bookCtrl.create.bind(bookCtrl));
  router.get("/book/search", bookCtrl.search.bind(bookCtrl));
  router.post("/book/update", bookCtrl.update.bind(bookCtrl));

  router.get("/book/del", bookCtrl.remove.bind(bookCtrl));

  router.get("/book/list", bookCtrl.getList.bind(bookCtrl));

  router.get("/store", async (req, res) => {
    console.log("🚀 ~ router.get ~ req.url:", req.url);

    // const qb = app.em
    //   .createQueryBuilder(Store, "shop")
    //   .select(["shop.*", "loc.*"])
    //   .leftJoin("shop.locationId", "loc")
    //   .where({ name: 1232 });

    const qb = app.em
      .createQueryBuilder(Store, "shop")
      .select("*")
      .leftJoinAndSelect("shop.locationId", "loc")
      .where({ name: 1232 });

    const conn = app.em.getConnection();
    const data = await conn.execute(
      "select * from store left join location on store.location_id = location.id where location.id = ?",
      [2]
    );

    const sql = qb.getQuery();

    const stores = await app.em.find(Store, {}, { populate: ["*"] });

    res.end(
      "hello store \n" +
        sql +
        "\n" +
        JSON.stringify(stores) +
        "\n ===== \n" +
        JSON.stringify(data)
    );
  });

  app.use(router);

  return router;
}
